<template>
    <view>
		<view class="product-top">
			<u-navbar
			    :back-icon-color="'#fff'" 
			    :border-bottom="false" 
			    :back-text-style="{color:'#fff'}" 
			    :title-color="'#ffffff'" 
			    back-text="返回" 
			    title="积分商城" 
			    :background="{ background: '#ffffff00' }"
			></u-navbar>
			
			<view class="background"></view>
			
			<view class="user-info">
			    <view class="credit-points">
			        {{userInfo.credit}} <text>分</text>
			    </view>
			    <view class="record-button" @click="navigateToExchangeRecord">兑换记录</view>
			</view>
			
			<view class="filter-container">
			    <view class="credit-range-filter">
			        <u-tabs 
			            :list="creditRangeList" 
			            :height="100" 
			            name="label" 
			            :bar-width="80"  
			            :active-color="'#EF7B3A'"	 
			            :is-scroll="true" 
			            :current="currentCreditRange" 
			            @change="onCreditRangeChange" 
			            style="width: 100%;"
			        ></u-tabs>
			    </view>
			    
			    <u-tabs 
			        :list="productCategoryList" 
			        :height="120" 
			        name="category" 
			        :bar-width="80"  
			        :active-color="'#EF7B3A'"	 
			        :is-scroll="productCategoryList.length < 5 ? false : true" 
			        :current="currentCategory" 
			        @change="onCategoryChange" 
			        style="width: 100%;"
			    ></u-tabs>
			</view>
		</view>
        
        <view class="product-list">
            <ProductList :PrList="productList" :isLoaded="isDataLoaded" />
            
            <!-- 合并加载更多提示 -->
            <view class="load-more">
                <view v-if="hasMoreData" class="load-more-animation">
                    <view class="loading-dot"></view>
                    <view class="loading-dot"></view>
                    <view class="loading-dot"></view>
                </view>
                <text>{{ hasMoreData ? '加载更多...' : '没有更多数据了' }}</text>
            </view>
        </view>
    </view>
</template>

<script>
    import { productCategory , creditProduct  } from '@/core/api/index.js'
    import { mapState } from 'vuex';
    export default {
        data() {
            return {
                creditRangeList: [
                    { label: '1-5000' },
                    { label: '5001-10000' },
                    { label: '10001-30000' },
                    { label: '30000以上' }
                ],
                productCategoryList: [
                    {
                        category: "全部"
                    }
                ],
                currentCategory: 0,
                currentCreditRange: 0,
                productList: [],
                isDataLoaded: false,
                isLoading: false,
                total: 0,
                currentPage: 1,  // 当前页码
                pageSize: 10,    // 每页数量
                hasMoreData: true, // 是否还有更多数据
                showLoadMore: false, // 是否显示加载更多提示
            }
        },
        computed: {
          ...mapState({
            userInfo: state => state.user.userInfo
          })
        },
        onLoad() {
            this.fetchProductCategories()
            this.fetchProducts()
        },
        
        // 监听页面滚动到底部
        onReachBottom() {
            console.log('触发上拉加载') // 添加日志以便调试
            if (this.isLoading || !this.hasMoreData) return
            this.loadMoreProducts()
        },
        
        methods: {
            async fetchProductCategories() {
                try {
                    const response = await productCategory()
                    this.productCategoryList = [...this.productCategoryList, ...response.data]
                } catch (error) {
                    console.error('获取商品分类失败:', error)
                }
            },
            
            onCategoryChange(index) {
                this.currentCategory = index
                this.resetAndFetch()
            },
            
            onCreditRangeChange(index) {
                this.currentCreditRange = index
                this.resetAndFetch()
            },
            
            navigateToExchangeRecord() {
                uni.navigateTo({
                    url: '/pages/my/exchange_order'
                })
            },
            
            // 重置分页并重新加载数据
            resetAndFetch() {
                this.currentPage = 1
                this.hasMoreData = true
                this.productList = []
                this.fetchProducts()
            },
            
            // 加载更多商品
            loadMoreProducts() {
                console.log('执行加载更多') // 添加日志以便调试
                this.currentPage++
                this.showLoadMore = true
                this.fetchProducts(true)
            },
            
            async fetchProducts(isLoadMore = false) {
                console.log('开始请求数据:', {isLoadMore, page: this.currentPage}) // 添加日志以便调试
                this.isLoading = true
                
                try {
                    const response = await creditProduct({ 
                        page: this.currentPage, 
                        size: this.pageSize,
                        condition: {
                            categoryId: this.productCategoryList[this.currentCategory]?.id,
                            minCredit: this.currentCreditRange == 0 ? 1 : (this.currentCreditRange == 1 ? 5001 : (this.currentCreditRange == 2 ?  10001 : 30000)),
                            maxCredit: this.currentCreditRange == 0 ? 5000 : (this.currentCreditRange == 1 ? 10000 : (this.currentCreditRange == 2 ?  30000 : 30000))
                        }
                    })
                    
                    console.log('数据请求成功:', response.data) // 添加日志以便调试
                    
                    const newProducts = response.data.records || []
                    this.total = response.data.total
                    
                    // 处理加载更多的情况
                    if (isLoadMore) {
                        this.productList = [...this.productList, ...newProducts]
                        
                        // 判断是否还有更多数据
                        if (newProducts.length < this.pageSize || this.productList.length >= this.total) {
                            this.hasMoreData = false
                        }
                    } else {
                        this.productList = newProducts
                        this.hasMoreData = newProducts.length >= this.pageSize
                    }
                    
                    this.isDataLoaded = true
                } catch (error) {
                    console.error('加载商品列表失败:', error)
                    
                    // 加载失败时回退页码
                    if (isLoadMore) {
                        this.currentPage--
                    }
                } finally {
                    this.isLoading = false
                    this.showLoadMore = this.hasMoreData
                }
            }
        }
    }
</script>

<style>
    page {
        background: #F8F8F8;
    }
</style>

<style lang="scss">
    ::v-deep .u-navbar-inner {
        margin-right: 0 !important;
    }
    .product-top{
        position: fixed;
        z-index: 1;
        top: 0%;
        width: 100%;
    }
    .background {
        background: url(https://img.shihhl.com/shequ/88_01.png) no-repeat;
        width: 100%;
        position: absolute;
        height: 25vh;
        top: 0%;
        z-index: -1;
    }
    
    .user-info {
        display: flex;
        padding: 50rpx 30rpx 30rpx;
        justify-content: space-between;
        
        .credit-points {
            font-size: 48rpx;
            color: #fff;
            
            text {
                font-size: 28rpx;
                margin-left: 5rpx;
            }
        }
        
        .record-button {
            width: 150rpx;
            height: 60rpx;
            border-radius: 30rpx;
            background-color: #fff;
            color: #EE5735;
            text-align: center;
            line-height: 60rpx;
        }
    }
    
    .filter-container {
        margin: 0 30rpx;
        background-color: #fff;
        border-radius: 20rpx;
        
        .credit-range-filter {
            padding: 20rpx 0rpx 0;
            width: 100%;
            display: flex;
            justify-content: space-between;
        }
    }
    
    .product-list {
        margin: 50rpx 30rpx;
		padding-top: 550rpx;
    }
    
    .load-more {
        text-align: center;
        padding: 20rpx 0;
        color: #999;
        font-size: 28rpx;
        
        .load-more-animation {
            display: flex;
            justify-content: center;
            margin-bottom: 10rpx;
            
            .loading-dot {
                width: 12rpx;
                height: 12rpx;
                margin: 0 6rpx;
                background-color: #EE5735;
                border-radius: 50%;
                animation: loading 1.4s infinite ease-in-out both;
            }
            
            .loading-dot:nth-child(1) { animation-delay: -0.32s; }
            .loading-dot:nth-child(2) { animation-delay: -0.16s; }
        }
    }
    
    @keyframes loading {
        0%, 80%, 100% { transform: scale(0); }
        40% { transform: scale(1); }
    }
</style>